package com.youtube.tutorial.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(urlPatterns="/XmlServlet", initParams={@WebInitParam(name="unameInit", value="Aiko Miyake")})
public class XmlServlet extends HttpServlet {

	String userName = null;

	private static final long serialVersionUID = 2L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter out = resp.getWriter();
		userName = req.getParameter("uname");

		HttpSession session = req.getSession();
		ServletContext context = req.getServletContext();
		if(userName != null && !userName.equals("")) {
			session.setAttribute("savedUser", userName);
			context.setAttribute("savedUser", userName);
		}
		out.println("Passed User (GET): " + userName);
		out.println("Passed User (from Session): " + session.getAttribute("savedUser"));
		out.println("Passed User (from Context): " + context.getAttribute("savedUser"));
		String fromInit = this.getServletConfig().getInitParameter("unameInit");
		out.println("Passed User (from Init): " + fromInit);
	
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter out = resp.getWriter();
		userName = req.getParameter("userFromPost");
		out.println("Passed User (POST): " + userName);
	}

}
